/*
 * Copyright (c) 2019. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.yawn.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

public class NettyClient {

    public static void main(String[] args) throws InterruptedException, IOException {

        NioEventLoopGroup clientGroup = new NioEventLoopGroup();
        Bootstrap client = new Bootstrap();
        client
                .group(clientGroup)
                .remoteAddress(new InetSocketAddress("localhost", 8080))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                        pipeline.addLast("decoder", new StringDecoder());
                        pipeline.addLast("encoder", new StringEncoder());
                        pipeline.addLast(new MyClientOutHandler());
                        pipeline.addLast(new MyClientInHandler());
                    }
                });

        ChannelFuture channelFuture = client.connect().sync();
        Channel channel = channelFuture.channel();
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while(true){
            channel.writeAndFlush(in.readLine() + "\r\n");
        }
//        channel.closeFuture().sync();
//        System.out.println("done!");
    }
}
